package April._23.answer.work7;

//如何确保A一定先打印
public class Main{
    private static Object o = new Object();

    public static void main(String[] args) {
        new Thread(() -> {
            // A线程打印奇数
            synchronized (o) {
                for (int i = 1; i <= 100; i += 2) {
                    System.out.println(Thread.currentThread().getName() + " " + i);
                    // 先唤醒B线程,再wait自己
                    o.notify();
                    try {
                        o.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                // A线程执行完毕时,B线程处于wait阻塞状态,所以为了让程序能够结束,在这里需要唤醒B线程
                o.notify();
            }
        }, "A线程").start();

        new Thread(() -> {
            // B线程打印偶数
            synchronized (o) {
                for (int i = 2; i <= 100; i += 2) {
                    System.out.println(Thread.currentThread().getName() + " " + i);
                    // 先唤醒A线程,再wait自己
                    o.notify();
                    try {
                        o.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                o.notify();
            }
        }, "B线程").start();
    }
}
